//
//  M4KeFuViewController.swift
//  M4
//
//  Created by Blankfein Prestamos on 2025/8/5.
//

import UIKit
import WebKit
import Photos
import AVFoundation
import MobileCoreServices

class M4KeFuViewController: M4BaseViewController,WKNavigationDelegate, WKScriptMessageHandler, WKUIDelegate ,UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    var  isCameraOpen: Bool = false
    var  isPhontoOpen: Bool = false
    let loading = M4LoadingAlertView()

    lazy var M4webView: WKWebView = {
        let preferences = WKPreferences()
        var webView = WKWebView(frame: CGRect(x: 0, y: Int(M4StatusBarHeight()), width: Int(M4ScreenWidth), height: Int(M4ScreenHeight) - Int(M4NavigationFullHeight())), configuration: M4webConfig)
        webView.scrollView.bounces = true
        webView.navigationDelegate = self
        webView.scrollView.showsVerticalScrollIndicator = false
        webView.scrollView.showsHorizontalScrollIndicator = false
        webView.scrollView.keyboardDismissMode = .interactive
        webView.scrollView.isScrollEnabled = true
        webView.uiDelegate = self
        return webView
    }()
    
    lazy private var M4webConfig: WKWebViewConfiguration = {
        let userContent = WKUserContentController()
        ["hgoweinoge", "jytdzzessA", "brehtttt"].forEach {
               userContent.add(self, name: $0)
           }
        let combinedScriptSource = """
        (function() {
            var meta = document.createElement('meta');
            meta.name = 'viewport';
            meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0';
            document.getElementsByTagName('head')[0].appendChild(meta);
            document.addEventListener('click', function(e) {
                if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') {
                    e.target.focus();
                }
            });
        })();
        """

        let script = WKUserScript(source: combinedScriptSource,
                                          injectionTime: .atDocumentEnd,
                                          forMainFrameOnly: true)
        userContent.addUserScript(script)
        let config = WKWebViewConfiguration()
        config.mediaTypesRequiringUserActionForPlayback = .all
        config.allowsInlineMediaPlayback = true
        config.userContentController = userContent
        let preference = WKPreferences()
        preference.javaScriptCanOpenWindowsAutomatically = true
        config.preferences = preference
        return config
    }()
    
    var M4urlStr : String = ""
    
//    override func viewWillAppear(_ animated: Bool) {
//        super.viewWillAppear(animated)
//        self.navigationController?.setNavigationBarHidden(true, animated: true)
//    }
//
//    override func viewWillDisappear(_ animated: Bool) {
//        super.viewWillDisappear(animated)
//        self.navigationController?.setNavigationBarHidden(false, animated: true)
//    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loading.M4LoadingAlertShow()
        cleanAndLoad(urlStr: "")
        
        view.addSubview(M4webView)
        M4NavTitle(M4Title: "Atención al cliente en línea", M4NavTitleColor: .white)

       
        
        
        
        
        // Do any additional setup after loading the view.
    }
    
    func cleanAndLoad(urlStr: String) {
          let types = Set([WKWebsiteDataTypeMemoryCache, WKWebsiteDataTypeDiskCache])
          WKWebsiteDataStore.default().removeData(ofTypes: types, modifiedSince: Date.distantPast) {
              guard let Url = URL(string:  self.M4urlStr ) else { return }
              let requesting = URLRequest(url: Url)
              self.M4webView.load(requesting)
          }
      }
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
       if message.name == "hgoweinoge" {
            self.navigationController?.popViewController(animated: true)
        }else if message.name == "jytdzzessA" {
            self.dismiss(animated: true)
            checkCameraAndPhotoPermission { granted in
                if granted {
                    print("相机和相册权限均已授权")
                    // 可以调用录像或拍照
                } else {
                    print("权限不足，无法使用相机或访问相册")
                }
            }
        }else if message.name == "brehtttt" {
            self.dismiss(animated: true)
            checkCameraAndPhotoPermission { granted in
                if granted {
                    print("相机和相册权限均已授权")
                    // 可以调用录像或拍照
                } else {
                    print("权限不足，无法使用相机或访问相册")
                }
            }

        }
    
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        loading.M4AlertViewHidden()
    }


    func checkCameraAndPhotoPermission(completion: @escaping (Bool) -> Void) {
        // 相机权限
        let cameraStatus = AVCaptureDevice.authorizationStatus(for: .video)
        let handleCamera = {
            // 相册权限
            if #available(iOS 14, *) {
                let photoStatus = PHPhotoLibrary.authorizationStatus(for: .readWrite)
                switch photoStatus {
                case .authorized, .limited:
                    completion(true)
                case .notDetermined:
                    PHPhotoLibrary.requestAuthorization(for: .readWrite) { newStatus in
                        DispatchQueue.main.async {
                            completion(newStatus == .authorized || newStatus == .limited)
                        }
                    }
                case .denied, .restricted:
                    completion(false)
                @unknown default:
                    completion(false)
                }
            } else {
                let photoStatus = PHPhotoLibrary.authorizationStatus()
                switch photoStatus {
                case .authorized:
                    completion(true)
                case .notDetermined:
                    PHPhotoLibrary.requestAuthorization { newStatus in
                        DispatchQueue.main.async {
                            completion(newStatus == .authorized)
                        }
                    }
                case .denied, .restricted:
                    completion(false)
                @unknown default:
                    completion(false)
                }
            }
        }

        switch cameraStatus {
        case .authorized:
            handleCamera()
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .video) { granted in
                DispatchQueue.main.async {
                    if granted {
                        handleCamera()
                    } else {
                        completion(false)
                    }
                }
            }
        case .denied, .restricted:
            completion(false)
        @unknown default:
            completion(false)
        }
    }
    private func handlePermissionsResult() {

        
        if !isCameraOpen {

        }
        if !isPhontoOpen {
        }

       

        

    }

}
